import {useState} from 'react';
import {Button, Col, Descriptions, message, Row, Table, Tabs, Tag} from 'antd';
import HttpRequest from "@/utils/HttpRequest";
import {defaultDomain} from "@/config/domain";
import {ModalForm} from '@ant-design/pro-form'
import ReactJson from 'react-json-view'
import onCopy, {FormatDateTime, ToStringByte} from "@/utils/DateTime";
import Popconfirm from 'antd/es/popconfirm'

const { TabPane } = Tabs
interface RecordTypes{
  key: any
  tag: any
  storeSize: any
  bornHost: string
  bornTimestamp: any
  storeTimestamp: any
  storeHost: any
  mv: boolean
  msgId: string
  topic: string
  queueId: number
  queueOffset: number,
  exceptionDesc:string,
  consumerGroup:string,
  timeStamp:number,
}

export function MessageDetail(prop: {
  record:RecordTypes
}) {
  const [msgDetail, setMsgDetail] = useState({})
  const [msgDataList, setMsgDataList] = useState([])
  const [trackDataList, setTrackDataList] = useState([])

  async function getMessage(record: { key?: any; tag?: any; storeSize?: any; bornHost?: string; bornTimestamp?: any; storeTimestamp?: any; storeHost?: any; mv?: boolean; msgId: any; topic: any; queueId?: number; queueOffset?: number; exceptionDesc?: string; messageTrackList?: any; messageBody?: any; isJson?: any; }) {
    // @ts-ignore
    let url =
      '/message/viewMessage.query?msgId=' +
      record.msgId +
      '&topic=' +
      record.topic
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'GET',
      params: {},
    })

    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    if (status === 0) {
      const resData = res.data
      if (resData) {
        const messageView = resData.messageView
        record.messageTrackList = resData.messageTrackList
        console.log('messageView', messageView)
        try {
          record.messageBody = JSON.parse(messageView.messageBody)
        } catch (e) {
          record.isJson = false
          record.messageBody = { '>': JSON.stringify(messageView.messageBody) }
        }
        setMsgDataList(record.messageTrackList)
        setMsgDetail(record.messageBody)
      }
    }
  }

  async function viewMessageTraceDetail() {
    // @ts-ignore
    let url =
      '/messageTrace/viewMessageTraceDetail.query?msgId=' +
      prop.record.msgId +
      '&topic=' +
      prop.record.topic
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'GET',
      params: {},
    })

    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    if (status === 0) {
      const resData = res.data
      if (resData) {
        setTrackDataList(resData)
      }
    }
  }

  async function sendMessage(groupId: string) {
    let url =
      '/message/consumeMessageDirectly.do?consumerGroup=' +
      groupId +
      '&msgId=' +
      prop.record.msgId +
      '&topic=' +
      prop.record.topic
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'POST',
      params: {},
    })

    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    if (status === 0) {
      message.success('消息重发成功！')
    } else {
      message.error('消息重发失败！>>' + res.errMsg)
    }
  }

  return (
    <ModalForm
      key="msgDetail"
      title={`消息ID [${prop.record.msgId}] 详情`}
      onVisibleChange={async (v) => {
        prop.record.mv = v
        if (v) {
          await getMessage(prop.record)
          await viewMessageTraceDetail()
        }
      }}
      trigger={<Button type="link">消息详情</Button>}
      width="80%"
      onFinish={async () => true}
    >
      <Tabs defaultActiveKey="1">
        <TabPane tab="消息详情" key="1">
          <Row gutter={24}>
            <Col span={24}>
              <Descriptions title="基本信息" bordered>
                <Descriptions.Item label="topic">
                  <div
                    onDoubleClick={() => {
                      onCopy(prop.record.topic, 'topic')
                    }}
                  >
                    {' '}
                    {prop.record.topic}
                  </div>
                </Descriptions.Item>
                <Descriptions.Item label="queueId">
                  {prop.record.queueId}
                </Descriptions.Item>
                <Descriptions.Item label="queueOffset">
                  {prop.record.queueOffset}
                </Descriptions.Item>

                <Descriptions.Item label="msgId">
                  <div
                    onDoubleClick={() => {
                      onCopy(prop.record.msgId, 'msgId')
                    }}
                  >
                    {prop.record.msgId}
                  </div>
                </Descriptions.Item>
                <Descriptions.Item label="发送端地址">
                  {prop.record.bornHost}
                </Descriptions.Item>
                <Descriptions.Item label="发送时间">
                  {FormatDateTime(prop.record.bornTimestamp / 1000)}
                </Descriptions.Item>
                <Descriptions.Item label="存储端地址">
                  {prop.record.storeHost}
                </Descriptions.Item>
                <Descriptions.Item label="存储时间">
                  {FormatDateTime(prop.record.storeTimestamp / 1000)}
                </Descriptions.Item>
                <Descriptions.Item label="消息大小">
                  {ToStringByte(prop.record.storeSize)}
                </Descriptions.Item>
              </Descriptions>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={22} style={{ marginTop: '5px' }}>
              <Descriptions title="消息详情" bordered>
                <Descriptions.Item>
                  <ReactJson
                    iconStyle="triangle"
                    collapsed={1}
                    theme="paraiso"
                    displayDataTypes={false}
                    displayObjectSize={false}
                    src={msgDetail}
                  />
                </Descriptions.Item>
              </Descriptions>
            </Col>
          </Row>
        </TabPane>
        <TabPane tab="消息轨迹" key="2">
          <Row gutter={24}>
            <Col span={24} style={{ marginTop: '10px', overflowY: 'auto' }}>
              <Table
                dataSource={msgDataList}
                style={{ height: '360px' }}
                pagination={{ pageSize: 10 }}
                columns={[
                  {
                    title: '消费组',
                    align: 'center',
                    width: '30%',
                    dataIndex: 'consumerGroup',
                    key: 'consumerGroup',
                    render: (text, record) => (
                      <div
                        style={{
                          wordWrap: 'break-word',
                          wordBreak: 'break-word',
                        }}
                        onDoubleClick={() => {}}
                      >
                        {text}
                      </div>
                    ),
                  },
                  {
                    title: '轨迹类型',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'trackType',
                    key: 'trackType',

                    render: (text, record) => {
                      // @ts-ignore
                      if (record.exceptionDesc) {
                        return <Tag color="yellow">{text}</Tag>
                      } else {
                        return <Tag color="green">{text}</Tag>
                      }
                    },
                  },
                  {
                    title: '错误描述',
                    align: 'center',
                    width: '20%',
                    dataIndex: 'exceptionDesc',
                    key: 'exceptionDesc',
                  },
                  {
                    title: '操作',
                    align: 'center',
                    width: '20%',
                    dataIndex: 'action',
                    key: 'action',
                    render: (text, record) => {
                      return (
                        <div style={{ cursor: 'pointer' }}>
                          <Popconfirm
                            title="是否消息重发?"
                            onConfirm={() => {
                              // @ts-ignore
                              sendMessage(record.consumerGroup)
                              return true
                            }}
                            okText="Yes"
                            cancelText="No"
                          >
                            <Button type="primary" danger size="small">
                              消息重发
                            </Button>
                          </Popconfirm>
                        </div>
                      )
                    },
                  },
                ]}
              />
            </Col>
          </Row>
        </TabPane>
        <TabPane tab="消息跟踪详细" key="3">
          <Row gutter={24}>
            <Col span={24} style={{ marginTop: '10px', overflowY: 'auto' }}>
              <Table
                dataSource={trackDataList}
                style={{ height: '360px' }}
                pagination={{ pageSize: 10 }}
                columns={[
                  {
                    title: '消息ID',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'msgId',
                    key: 'msgId',
                    render: (text, record) => (
                      <div
                        onDoubleClick={() => {
                          onCopy(text, '消息ID')
                        }}
                        style={{
                          wordWrap: 'break-word',
                          wordBreak: 'break-word',
                        }}
                      >
                        {text}
                      </div>
                    ),
                  },
                  {
                    title: '主题',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'topic',
                    key: 'topic',
                    render: (text, record) => (
                      <div
                        onDoubleClick={() => {
                          onCopy(text, 'topic')
                        }}
                        style={{
                          wordWrap: 'break-word',
                          wordBreak: 'break-word',
                        }}
                      >
                        {text}
                      </div>
                    ),
                  },
                  {
                    title: 'tags',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'tags',
                    key: 'tags',
                  },

                  {
                    title: '分组名称',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'groupName',
                    key: 'groupName',
                    render: (text, record) => (
                      <div
                        onDoubleClick={() => {
                          onCopy(text, 'groupName')
                        }}
                        style={{
                          wordWrap: 'break-word',
                          wordBreak: 'break-word',
                        }}
                      >
                        {text}
                      </div>
                    ),
                  },

                  {
                    title: '消息类型',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'msgType',
                    key: 'msgType',
                  },
                  {
                    title: '消息ID偏移量',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'offSetMsgId',
                    key: 'offSetMsgId',
                    render: (text, record) => (
                      <div
                        onDoubleClick={() => {
                          onCopy(text, 'offSetMsgId')
                        }}
                        style={{
                          wordWrap: 'break-word',
                          wordBreak: 'break-word',
                        }}
                      >
                        {text}
                      </div>
                    ),
                  },
                  {
                    title: '发送端地址',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'storeHost',
                    key: 'storeHost',
                  },
                  {
                    title: '创建时间',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'timeStamp',
                    key: 'timeStamp',
                    render: (text, record:RecordTypes) => (
                      <div
                        style={{
                          wordWrap: 'break-word',
                          wordBreak: 'break-word',
                        }}
                        onDoubleClick={() => {}}
                      >

                        {FormatDateTime(record.timeStamp / 1000)}
                      </div>
                    ),
                  },

                  {
                    title: '消耗时间',
                    align: 'center',
                    width: '10%',
                    dataIndex: 'costTime',
                    key: 'costTime',
                  },
                ]}
              ></Table>
            </Col>
          </Row>
        </TabPane>
      </Tabs>
    </ModalForm>
  )
}
